package code;

public class Code19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
    	int size=0;
    	ListNode p=head;
    	while(p!=null){
    		size++;
    		p=p.next;
    	}
    	n=size-n;
    	p=head;
    	ListNode pre=null;
    	while(p!=null){
    		if(n==0){
    			if(pre==null){
    				head=head.next;
    			}
    			else 
    				pre.next=p.next;
    			break;
    		}
    		n--;
    		pre=p;
    		p=p.next;
    	}
        return head;
    }
    public static void main(String[] args){
    	ListNode head=new ListNode(1);
    	ListNode node2=new ListNode(2);
    	ListNode node3=new ListNode(3);
    	ListNode node4=new ListNode(4);
    	ListNode node5=new ListNode(5);
    	head.next=node2;
    	node2.next=node3;
    	node3.next=node4;
    	node4.next=node5;
    	head=new Code19().removeNthFromEnd(head, 2);
    	while(head!=null){
    		System.out.print(head.val+"-->");
    		head=head.next;
    	}
    	System.out.println();
    }
}
